//
//  HSYBalanceViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/7.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYBalanceViewController.h"
#import "HSYBalanceHeaderView.h"
#import "HSYBalanceTableHeaderView.h"
#import "UIColor+hsyTheme.h"
#import "UIImage+Tools.h"
#import "HSYGetWithDrawRecordsRequest.h"
#import "HSYWithDrawRecordsModel.h"
#import "HSYBalanceCell.h"
#import "HSYWithDrawViewController.h"

#define kHeaderViewHeight 212.0

static NSString *const cellReuseIdentifier = @"cellReuseIdentifier";

@interface HSYBalanceViewController ()<HSYBalanceHeaderViewDelegate>

@property(nonatomic,strong)HSYBalanceHeaderView *header;
@property(nonatomic,strong)HSYWithDrawRecordsModel *dataModel;

@end

@implementation HSYBalanceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"HSYBalanceCell" bundle:nil] forCellReuseIdentifier:cellReuseIdentifier];

    [self.titleButton setTitle:@"我的余额" forState:UIControlStateNormal];
    self.tableView.tableFooterView = [[UIView alloc] init];

    HSYBalanceTableHeaderView *tableHeader = [[[NSBundle mainBundle] loadNibNamed:@"HSYBalanceTableHeaderView" owner:nil options:nil] firstObject];
    tableHeader.frame = CGRectMake(0, 0, ScreenWidth(), 79);
    self.tableView.tableHeaderView = tableHeader;

    [self addBalanceHeadrView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshBalance:) name:kNotificationRefreshBalance object:nil]; //更新余额
    
    [self hsy_headerBeginRefreshing];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //如果用户已登录，请求账户信息
    if ([HSYUserCenter instatce].appAuUser.uid.length) {
        [[HSYUserCenter instatce] getBalanceSuccess:nil failure:nil];
    }
}

- (void)setupNavigationBarBackgroundImage{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[UIImage new];

}

- (BOOL)hsy_showEmptyImage{
    return NO;
}

- (UIEdgeInsets)hsy_tableViewEdgeInsets{
    return UIEdgeInsetsMake(kHeaderViewHeight, 0, 0, 0);
}

- (void)hsy_loadServerData{
    [super hsy_loadServerData];

    if (self.pageIdex == 0) { //刷新数据，请求第一页
        self.pageIdex= self.pageIdex + 1;
    }
    
    HSYGetWithDrawRecordsRequest *task = [[HSYGetWithDrawRecordsRequest alloc] init];
    task.accountId = [HSYUserCenter instatce].appAuUser.accountID;
    task.pageNo = self.pageIdex;
    task.pageSize = self.pageStep;
    
    __weak typeof(self)weakSelf = self;

    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        [weakSelf hsy_headerEndRefreshing];
        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            HSYWithDrawRecordsModel *recordsModel = [HSYWithDrawRecordsModel mj_objectWithKeyValues:response.encryptDataResult];
            
            if (weakSelf.pageIdex != 1) { //为1是为下拉刷新
                [weakSelf.dataModel.records addObjectsFromArray:recordsModel.records];
                recordsModel.records = weakSelf.dataModel.records;
                
            }
            weakSelf.dataModel = recordsModel;
            
            if (recordsModel.totalPage <= weakSelf.pageIdex) {//没有更多数据
                [weakSelf hsy_loadServerDataComplete:kDataLoadCompleteStatusNoMoreData];
            }else{
                [weakSelf hsy_loadServerDataComplete:kDataLoadCompleteStatusDefault];
            }
            
        }else{
            [weakSelf showMessage:response.resultMessage];
            [weakSelf hsy_loadServerDataComplete:kDataLoadCompleteStatusNoMoreData];
        }
    } failure:^(NSError *error) {
        [weakSelf hsy_headerEndRefreshing];
        [weakSelf showMessage:@"请求超时"];
        [weakSelf hsy_loadServerDataComplete:kDataLoadCompleteStatusFailed];

    }];
}

- (void)addBalanceHeadrView{
    HSYBalanceHeaderView *vi = [[[NSBundle mainBundle] loadNibNamed:@"HSYBalanceHeaderView" owner:nil options:nil] firstObject];
    vi.frame = CGRectMake(0, -212, ScreenWidth(), kHeaderViewHeight);
    vi.delegate = self;
    self.header = vi;
    [self.view addSubview:vi];
    
    [vi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.right.mas_equalTo(self.view.mas_right);
        make.left.mas_equalTo(self.view.mas_left);
        make.height.mas_equalTo(kHeaderViewHeight);
    }];
    
    [self refreshBalance:nil];
}

- (void)refreshBalance:(NSNotification *)notifi{
    self.header.totalAmountLabel.text = [NSString stringWithFormat:@"%@",[HSYUserCenter instatce].totalAmount.length?[HSYUserCenter instatce].totalAmount:@"0.00"];
    self.header.dueSettleAmountLabel.text = [NSString stringWithFormat:@"待结算金额：%@元",[HSYUserCenter instatce].dueSettleAmount.length?[HSYUserCenter instatce].dueSettleAmount:@"0.00"];
    self.header.availableAmountLabel.text = [NSString stringWithFormat:@"可提现金额：%@元",[HSYUserCenter instatce].available.length?[HSYUserCenter instatce].available:@"0.00"];
}

#pragma mark - UIScrollViewDelegate -

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (scrollView.contentOffset.y < -kHeaderViewHeight) {
//        self.header.frame = CGRectMake(0, scrollView.contentOffset.y, self.header.frame.size.width, self.header.frame.size.height);
//    }else{
//        self.header.frame = CGRectMake(0, -kHeaderViewHeight, self.header.frame.size.width, self.header.frame.size.height);
//    }
//    
//    if (scrollView.contentOffset.y > -60) {
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"4b65a5"] size:CGSizeMake(1, 1)]  forBarMetrics:UIBarMetricsDefault];
//    }else{
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor] size:CGSizeMake(1, 1)] forBarMetrics:UIBarMetricsDefault];
//    }
//    
//}

#pragma mark UITableViewDelegate,UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataModel.records.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 38.0;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HSYWithDrawRecordModel *model = self.dataModel.records[indexPath.row];
    
    HSYBalanceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.timeLabel.text = [NSString dateStringFrom1970:model.settleDate/1000 formatter:@"YYYY-MM-dd"];
    cell.numberLabel.text = [NSString stringWithFormat:@"%ld笔",(long)model.number];
    cell.amountLabel.text = [NSString stringWithFormat:@"%.2f元",model.settleAmount];

    return cell;
    
}



#pragma mark - HSYBalanceHeaderViewDelegate -

- (void)handleWithDraw{
    HSYWithDrawViewController *vc = [[HSYWithDrawViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
